package com.sneakxy.mybatis.commons.repository.query.executor;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.TextSqlNode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;

import com.sneakxy.mybatis.commons.orm.MybatisEntityManager;
import com.sneakxy.mybatis.commons.orm.generation.GenerationManager;
import com.sneakxy.mybatis.commons.orm.mapping.MybatisColumn;
import com.sneakxy.mybatis.commons.repository.query.parser.MybatisPartTree;
import com.sneakxy.mybatis.commons.utils.MybatisUtils;

/**
 * @author 潜行的青衣
 */
public class FindAllPageRepositoryExecutor<T> extends AbstractRepositoryExecutor<Page<T>> {

	private String countStatement;
	
	/**
	 * @param entityManager
	 * @param loader
	 * @param method
	 * @param type
	 */
	public FindAllPageRepositoryExecutor(MybatisEntityManager entityManager, Class<?> loader, String method,
			Class<?>... type) {
		super(entityManager, loader, method, type);
	}

	/**
	 * @param entityManager
	 * @param method
	 */
	public FindAllPageRepositoryExecutor(MybatisEntityManager entityManager, Method method) {
		super(entityManager, method);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.repository.query.executor.RepositoryExecutor#execute(java.lang.Object[])
	 */
	@Override
	public Page<T> execute(Object... parameters) {
		Object parameterObject = this.createParameterObject(parameters, false);
		List<T> list = this.getEntityManager().getSqlSessionTemplate().selectList(getStatement(), parameterObject);
		parameterObject = this.createParameterObject(parameters, true);
		Long count = this.getEntityManager().getSqlSessionTemplate().selectOne(getCountStatement(), parameterObject);
		return new PageImpl<T>(list, MybatisUtils.getPageable(parameters), count);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.repository.query.executor.AbstractRepositoryExecutor#onBuildStatment()
	 */
	@Override
	protected void onBuildStatment() {
		String statement = StringUtils.remove(this.getStatement(), this.getEntityManager().getCurrentNamespace());
		this.countStatement = this.getEntityManager().getNamespacedId(new StringBuilder().append("count-").append(statement).toString());
		this.onBuildListStatement();
		this.onBuildCountStatement();
	}
	
	protected void onBuildCountStatement() {
		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append("SELECT COUNT(*) ").append(" FROM ${").append(MybatisPartTree.GENERIC_NAME_PREFIX).append("1} ");
		String id = this.getCountStatement();
		String sql = sqlBuilder.toString();
		SqlCommandType sqlCommandType  = SqlCommandType.SELECT;
		SqlSource sqlSource = new DynamicSqlSource(this.getEntityManager().getConfiguration(), new TextSqlNode(sql));
		this.getEntityManager().addMappedStatement(id, sqlSource, sqlCommandType, ParamMap.class, Long.class);
	}
	
	protected void onBuildListStatement() {
		GenerationManager generationManager = this.getEntityManager().getGenerationManager();
		StringBuilder sqlBuilder = new StringBuilder();
		List<MybatisColumn> columns = this.getEntityManager().getEntityColumns(MybatisPartTree.GENERIC_NAME_PREFIX + "1");
		Iterator<MybatisColumn> it = columns.iterator();
		MybatisColumn column = null;
		sqlBuilder.append("SELECT ");
		while(it.hasNext()) {
			column = it.next();
			sqlBuilder.append(generationManager.formatColumnName(column.getColumn()));
			if(it.hasNext()) {
				sqlBuilder.append(",");
			}
		}
		sqlBuilder.append(" FROM ${").append(MybatisPartTree.GENERIC_NAME_PREFIX).append("1} ");
		String id = this.getStatement();
		String sql = sqlBuilder.toString();
		SqlCommandType sqlCommandType  = SqlCommandType.SELECT;
		SqlSource sqlSource = new DynamicSqlSource(this.getEntityManager().getConfiguration(), new TextSqlNode(sql));
		Class<?> domainClass = this.getEntityManager().getEntityInformation().getJavaType();
		String resultMapName = domainClass.getSimpleName();
		this.getEntityManager().addMappedStatement(id, sqlSource, sqlCommandType, ParamMap.class, resultMapName, domainClass);
	}

	protected void setCountStatement(String countStatement) {
		this.countStatement = countStatement;
	}

	protected String getCountStatement() {
		return countStatement;
	}

}
